
const PORT = 8000;
const { Pool } = require('pg');
const pool = new Pool({
    user: 'postgres',
    host: 'project_data_base',
    //host: '127.0.0.1',
    database: 'postgres',
    password: '1234',
    port: 5432,
  });
class equipment {
  /**
     * @swagger
     * components:
     *   schemas:
     *     Equipment:
     *       type: object
     *       properties:
     *         eid:
     *           type: integer
     *         ename:
     *           type: string
     *         id_subtypes:
     *           type: integer
     *         id_mode:
     *           type: integer
     * 
     * /equipment:
     *   get:
     *     tags: [Оборудование]
     *     summary: Получение списка оборудования
     *     parameters:
     *       - in: query
     *         name: limit
     *         schema:
     *           type: integer
     *         description: Лимит записей
     *       - in: query
     *         name: offset
     *         schema:
     *           type: integer
     *         description: Смещение записей
     *     responses:
     *       200:
     *         description: Список оборудования
     *         content:
     *           application/json:
     *             schema:
     *               type: object
     *               properties:
     *                 equipments:
     *                   type: array
     *                   items:
     *                     $ref: '#/components/schemas/Equipment'
     *                 next:
     *                   type: string
     *                   nullable: true
     *                 previous:
     *                   type: string
     *                   nullable: true
     *       500:
     *         description: Внутренняя ошибка сервера
     */
    async equipmentGet (req, res) {
          try {
            const limit = req.query.limit || 10;
            const offset = req.query.offset || 0;
            const values = [];
            const free = req.query.free;
        
            let queryText = `
              SELECT * FROM equipment as eq join modes as m on m.id=eq.id_mode join subtypes as st on eq.id_subtypes=st.id join types as t on st.type_id=t.id
            `;

            if(free){
             queryText = `
              SELECT * FROM equipment as eq join modes as m on m.id=eq.id_mode join subtypes as st on eq.id_subtypes=st.id join types as t on st.type_id=t.id where eq.free = true
            `;
            }
        
            const result = await pool.query(queryText, values);
            const equipments = result.rows;
            console.log(equipments)
            const nextOffset = equipments.length < limit ? 0 : parseInt(offset) + parseInt(limit);
            const previousOffset = parseInt(offset) - parseInt(limit) >= 0 ? parseInt(offset) - parseInt(limit) : null;
        
            const response = {
                equipments,
              next: nextOffset === 0 ? null : `http://localhost:${PORT}/equipment?limit=${limit}&offset=${nextOffset}`,
              previous: previousOffset === null? null : `http://localhost:${PORT}/equipment?limit=${limit}&offset=${previousOffset}`,
            };
        
            res.json(response);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
        /**
     * @swagger
     * /equipment:
     *   post:
     *     tags: [Оборудование]
     *     summary: Создание нового оборудования
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             properties:
     *               ename:
     *                 type: string
     *               id_subtypes:
     *                 type: integer
     *               id_mode:
     *                 type: integer
     *     responses:
     *       200:
     *         description: Новое оборудование создано
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/Equipment'
     *       500:
     *         description: Внутренняя ошибка сервера
     */
    async equipmentPost (req, res){
          try {
            const { ename, id_subtypes, id_mode, on,code, comment } = req.body;
        
            const queryText = `
              INSERT INTO equipment (eid, ename, id_subtypes, id_mode, off, code, comment)
              VALUES (DEFAULT, $1, $2, $3, $4, $5, $6)
              RETURNING *;
            `;
            const values = [ename, id_subtypes, id_mode, on, code, comment];
            console.log(values)
            const result = await pool.query(queryText, values);
            const newEquipment = result.rows[0];
        
            res.json(newEquipment);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
}

module.exports = new equipment()